<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Article;
use App\Model\Tag;
use App\Http\Requests\ArticleRequest;
use App\Admin;
use Auth;
use DB;
use App\Model\Pic;

class ArticleController extends Controller
{
    public function index(){
        
        $list=Article::with("firstPic")->with("morePic")->with("articletag")->paginate(10);
        return view("admin/article/index",['list'=>$list]);
    }

    public function create(){
        $tag=Tag::where('type','article')->where('status',">=",0)->get();
        return view('admin/article/create',['tag'=>$tag]);
    }

    public function store(ArticleRequest $request){
        $data=$request->intersect('title','description','author','visit_cnt','type','post_lock','more_pic','content');
        $tag_id=$request->tag_id;
        $data['pic']=$request->first_pic;
        $data['publish_id']=Auth::guard('admin')->user()->id;
        $more_pic=$request->input('more_pic','');
        DB::beginTransaction();
        try{
            $Article=Article::create($data);
            $Article->articletag()->sync($tag_id);
            if($more_pic){
                foreach ($more_pic as $v){
                    $pic=Pic::find($v);
                    $pic->related_id=$Article->id;
                    $pic->update();
                }
            }
        }catch (\Exception $e){
            DB::rollback();
            return parent::error('创建失败');
        }
        DB::commit();
        return parent::success('success',Route('admin.article.index'));


    }

    public function edit(){

    }

    public function update(){

    }

    public function destroy(){

    }

    public function publish($id)
    {
        
        Article::where('id',$id)->update(['status'=>'1']);
        return parent::success('success',route('admin.item.index'));
        
    }

    public function unpublish($id)
    {
        
        Article::where('id',$id)->update(['status'=>'0']);
        return parent::success('success',route('admin.item.index'));
        
    }
}
